<?php

namespace api\controllers;

use yii\web\Controller;

class CommonController extends Controller {

    public $enableCsrfValidation = false;
    public $key = "key-software";

    /**
     * check login
     */
    public function checkLogin() {
        $pass = true;
        $header = \Yii::$app->request->getHeaders();
        if (!$header->has('token') || !$header->has('user') || !$header->has('authorized')) {
            $pass = false;
            $message = "request is invalid!";
        } else {
            $method = $_SERVER['REQUEST_METHOD'];
            $body = $requestUri = "http://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
            if ($method == "POST") {
                $body = @file_get_contents('php://input');
            }
            $string = $header->get('token') . ":panda@cash:" . $header->get('user') . ":" . $body;
            if($header->get('authorized') != md5($string)){
              $pass = false;
              $message = "authentication fail!";
            } 
        }

        if (!$pass) {
            $this->setHeader(200);
            echo json_encode(array('total' => 0, 'status' => 'error', 'message' => $message, 'objects' => null));
            exit();
        }
    }

    /*
     * 
     */

    protected function setHeader($status) {

        $status_header = 'HTTP/1.1 ' . $status . ' ' . $this->_getStatusCodeMessage($status);
        $content_type = "application/json; charset=utf-8";

        header($status_header);
        header('Content-type: ' . $content_type);
        header('X-Powered-By: ' . "Nintriva <nintriva.com>");
    }

    /**
     * 
     * @param type $status
     * @return type
     */
    protected function _getStatusCodeMessage($status) {
        $codes = Array(
            200 => 'OK',
            400 => 'Bad Request',
            401 => 'Unauthorized',
            402 => 'Payment Required',
            403 => 'Forbidden',
            404 => 'Not Found',
            500 => 'Internal Server Error',
            501 => 'Not Implemented',
        );
        return (isset($codes[$status])) ? $codes[$status] : '';
    }

    /**
     * 
     */
    public function parserMessage($messages) {
        $message_string = "";
        if(is_array($messages)){
            foreach ($messages as $values) {
                if (is_array($values)) {
                    $message_string .= implode("\n", $values);
                } else {
                    $message_string .= $values . "\n";
                }
            }
        }else{
            $message_string = $messages;
        }
        
        return $message_string;
    }

}
